# -*- coding: UTF-8 -*-
#!/usr/bin/env python

import datetime
from flask import Flask, render_template, session, redirect, url_for,flash
from flask.ext.script import Manager
import traceback
from pymongo.mongo_client import MongoClient
from flask.ext.bootstrap import Bootstrap

from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

from jd import trackprod

app = Flask(__name__)
app.config['SECRET_KEY'] = 'bush'

manager = Manager(app)
bootstrap = Bootstrap(app)

@app.route('/wea/<day>')
def index(day):
    tem = MongoClient().contact.weather.find_one({"day":day})
    print tem
    return render_template('hello.html',tem=tem)

@app.route('/wea/now')
def weanow():
    today = datetime.date.today()
    strd = today.strftime('%Y%m%d')
    tem = MongoClient().contact.weather.find_one({"day":strd})
    print tem
    return render_template('today.html',tem=tem)

@app.route('/wea7d/<city>')
def wea7d(city):
    tems = []
    try:
        tems = MongoClient().contact.weather.find({})
        print tems
    except Exception:
        traceback.print_exc()
    return render_template('wea7d.html', tems=tems)

@app.route('/snatch/prods')
def snatch_prods():
    prods = MongoClient().contact.trackproduct.find({})
    return render_template('snatchjd.html',prods=prods)

@app.route('/snatch/jd/form', methods=['GET', 'POST'])
def snatch_jd_form():
    prodid = None
    form = TrackForm()
    if form.validate_on_submit():
        prodid = form.prodid.data
        if len(prodid)>0:
            trackprod(prodid)
        old_prodid = session.get('prodid')
        if old_prodid is not None and old_prodid != form.prodid.data:
            flash('prodID=%s'%(prodid))
        session['prodid'] = prodid
        form.prodid.data = ''
        redirect(url_for('snatch_jd_form'))
    return render_template('snatchjdform.html', form=form, prodid=session['prodid'])



#---------------以上接口定义完成-------------------------------

class TrackForm(Form):
    prodid = StringField('prod ID?', validators=[Required()])
    submit = SubmitField('submit')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

if __name__ == '__main__':
    manager.run()
